<?php

$ARGV_FLAG = $argv[1];
if (!$ARGV_FLAG) {
    $ARGV_FLAG = 0;
}

$localIp = file_get_contents('http://imail.sinaapp.com/ip.php');
if (!$localIp) {
    $localIp = file_get_contents('http://imail.sinaapp.com/ip.php');
}

//每天执行2次
require_once dirname(__FILE__) . '/autoload.php';

function post_email_by_sae($title, $body, $users) {
    if (!is_array($users)) {
        $users = explode(',', $users);
    }

    $api = 'http://imail.sinaapp.com/sapi.php';
    $data = array(
        'title' => $title,
        'body' => $body,
        'to' => implode(',', $users)
    );

    $post_variables = $data;
    $content = http_build_query($post_variables);
    $content_length = strlen($content);
    $options = array(
        'http' => array(
            'method' => 'POST',
            'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
            "Content-length: $content_length\r\n",
            'content' => $content,
            'timeout' => 60,
        )
    );
    $context = stream_context_create($options);

    return file_get_contents($api, false, $context);
}

$timeStart = time();

$GlobalResultData = array();

$ShouRuData = array();
if (file_exists(dirname(__FILE__) . '/report.csv')) {
    $fp = fopen(dirname(__FILE__) . '/report.csv', 'r');
    $INDEX = 0;
    while ($dataline = fgets($fp)) {
        if (!$INDEX) {
            $INDEX++;
            continue;
        }
        $dataline = explode("\t", $dataline);
        $dataline[0] = preg_replace('#\s+#', '', $dataline[0]);
        $ShouRuData[$dataline[0]] = preg_replace('#\s+#', '', $dataline[6]);
        $INDEX++;
    }
    fclose($fp);
}


$s = '';
if (file_exists(dirname(__FILE__) . '/domainlist.txt')) {
    $s = file_get_contents(dirname(__FILE__) . '/domainlist.txt');
}

$domainlist = array_filter(explode('<br />', nl2br(trim($s))));
foreach ($domainlist as &$ds) {
    $ds = preg_replace('#\s+#', '', $ds);
}unset($ds);
$domainlist = array_filter($domainlist);

$locallockfile = dirname(__FILE__) . '/locklist.php';
if (!file_exists($locallockfile)) {
    log::e('!file_exists($locallockfile)', true, true);
    die();
}
$lockdomains = json_decode(file_get_contents($locallockfile), true);
$arrUniqDomainDataUniq = array();
$arrUniqDomainDataWWW = array_merge($domainlist, $lockdomains);


if ($ARGV_FLAG) {
    $locallockfile = dirname(__FILE__) . '/locklist_' . $ARGV_FLAG . '.php';
    if (!file_exists($locallockfile)) {
        log::e('!file_exists($locallockfile)', true, true);
        die();
    }
    $lockdomains = json_decode(file_get_contents($locallockfile), true);
    $arrUniqDomainDataWWW = $lockdomains;
}


foreach ($arrUniqDomainDataWWW as $domainALL) {
    $arrDInfo = explode('.', $domainALL);
    $length = count($arrDInfo);
    $extk = $length - 1;
    $dok = $length - 2;
    $domain = $arrDInfo[$dok] . '.' . $arrDInfo[$extk];
    if (is_numeric($arrDInfo[$extk])) {
        log::w($domain);
        continue;
    }
    $arrUniqDomainDataUniq[] = $domainALL;
}

$arrUniqDomainDataUniq = array_filter($arrUniqDomainDataUniq);
$arrUniqDomainDataUniq = array_unique($arrUniqDomainDataUniq);

$TotalCount = count($arrUniqDomainDataUniq);
$WarningCount = 0;

$HTMLBODY = '';
$HTMLBODY.= '<b>定时检测报警报告(' . $TotalCount . '个)[Stat By '.$localIp.']</b>
          <table border="1" width="100%" bordercolorlight="#C0C0C0" bordercolordark="#C0C0C0" style="border-collapse: collapse;font-size: 14px;">';
$HTMLBODY.='<tr height="35">
    <td width="150">域名&nbsp;</td>
    <td width="150">发生时间&nbsp;</td>
    <td width="100">手工Check&nbsp;</td>
    <td width="100">Response</td>
    <td width="100">上次是否正常</td>
    <td width="100">单次请求耗时</td></tr>
    ';

$isNeedSendWarningEmail = false;

foreach ($arrUniqDomainDataUniq as $domain) {
    $checkResFileSave = APP_DATA_PATH . 'resultsave/' . $domain . '.txt';
    fCheckDir($checkResFileSave);
    $prevResContent = file_get_contents($checkResFileSave);
    $sonTimeStart = time();
    $curl = 'http://' . $domain . '/kapi.php?act=onlinecheck';
    $sContent = file_get_contents($curl);
    $flag = false;
    $color = ' color="green" ';
    $result = '';
    $http_status_code = 0;
    foreach ($http_response_header as $v) {
        if (strpos($v, '200 OK') && ($sContent == 'success' || $sContent == '<pre>success')) {
            log::n('Success:' . $curl . '|' . $v, true, true);
            $http_status_code = 200;
            $flag = true;
        }
    }
    if (strpos($sContent, '_news') || strpos($sContent, 'empty') || 'Operation can not be empty' == $sContent) {
        $flag = true;
        $sContent = 'msuccess';
    }
    if (!$flag) {
        $snoopyFetchContent = snoopy_fetch($curl);
        if ($snoopyFetchContent == 'success' || $snoopyFetchContent == '<pre>success') {
            log::n('Success:' . $curl . '|' . $v, true, true);
            $http_status_code = 200;
            $flag = true;
        }
    }
    if (!$flag) {
        $WarningCount++;
        $color = ' color="red" ';
        log::n('Error:' . $curl . '|' . $v, true, true);
        $time = time();
        $lockFile = APP_DATA_PATH . $domain . '_ErrorEmailSendLock.txt';
        if (file_exists($lockFile)) {
            $preTime = file_get_contents($lockFile);
        } else {
            $preTime = 0;
        }
        if ($time - $preTime > 1800) {
            $isNeedSendWarningEmail = true;
            file_put_contents($lockFile, $time);
        }
    }

    if ($sContent && $sContent != 'success' && 'msuccess' != $sContent && '<pre>success' != $sContent) {
        $sContent = 'NoEmpty';
    }
    if ($snoopyFetchContent && $snoopyFetchContent != 'success' && '<pre>success' != $snoopyFetchContent) {
        $snoopyFetchContent = 'NoEmpty';
    }

    file_put_contents($checkResFileSave, $sContent . '/' . $snoopyFetchContent);

    global $http_status_code;
    $sonTimeEnd = time();

    if ($color != ' color="red" ') {
        $GlobalResultData['green'][] = '<tr height="35">
    <td width="150"><font' . $color . '>' . $domain . '</font>[' . $ShouRuData[$domain] . ']</td>
    <td width="150">' . date('Y-m-d H:i:s') . '</td>
    <td width="100"><a href="' . $curl . '" target="_blank">手工检测</a></td>
    <td width="100"><font' . $color . '>' . $sContent . '/' . $snoopyFetchContent . '</font>[' . $http_status_code . ']&nbsp;</td>
    <td width="100">' . $prevResContent . '</td>
    <td width="100"><font' . $color . '>' . ($sonTimeEnd - $sonTimeStart) . '秒</font>&nbsp;</td></tr>
    ';
    } else {
        $GlobalResultData['red'][] = '<tr height="35">
    <td width="150"><font' . $color . '>' . $domain . '</font>[' . $ShouRuData[$domain] . ']</td>
    <td width="150">' . date('Y-m-d H:i:s') . '</td>
    <td width="100"><a href="' . $curl . '" target="_blank">手工检测</a></td>
    <td width="100"><font' . $color . '>' . $sContent . '/' . $snoopyFetchContent . '</font>[' . $http_status_code . ']&nbsp;</td>
    <td width="100">' . $prevResContent . '</td>
    <td width="100"><font' . $color . '>' . ($sonTimeEnd - $sonTimeStart) . '秒</font>&nbsp;</td></tr>
    ';
    }
}

foreach ($GlobalResultData['red'] as $html) {
    $HTMLBODY.=$html;
}

foreach ($GlobalResultData['green'] as $html) {
    $HTMLBODY.=$html;
}

if ($isNeedSendWarningEmail) {
    $HTMLBODY.='</table>';
    $arrUsers = array(
        'think889977@yeah.net',
    );
    $timeEnd = time();
    $HTMLBODY.='<hr />总计耗时:' . ($timeEnd - $timeStart) . '秒<hr />';
    post_email_by_sae('[警告:' . $WarningCount . ']HTTP监控访问报警[' . date('Y-m-d H:i:s') . '][flag:' . $ARGV_FLAG . ']', $HTMLBODY, $arrUsers);
} else {
    //发送正常邮件报告
    $time = time();
    $lockFile = APP_DATA_PATH . 'OKSendLock.txt';
    if (file_exists($lockFile)) {
        $preTime = file_get_contents($lockFile);
    } else {
        $preTime = 0;
    }
    if ($time - $preTime > 3600) {
        file_put_contents($lockFile, $time);
        $HTMLBODY.='</table>';
        $arrUsers = array(
            'think889977@yeah.net',
        );
        $timeEnd = time();
        $HTMLBODY.='<hr />总计耗时:' . ($timeEnd - $timeStart) . '秒<hr />';
        post_email_by_sae('HTTP监控访问正常[' . date('Y-m-d H:i:s') . '][flag:' . $ARGV_FLAG . ']', $HTMLBODY, $arrUsers);
    }
}
?>
